package com.tyrone.captcha.exception;

import com.tyrone.captcha.entity.Response;
import com.tyrone.captcha.entity.constant.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xieyl
 * @create 2021/11/17 15:08
 */
@RestControllerAdvice
@Slf4j
public class ResponseExceptionHandler {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response handlerMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        List<String> results = new ArrayList<>();
        for (FieldError fieldError : fieldErrors) {
            log.error("参数：{}异常，{}",fieldError.getField(),fieldError.getDefaultMessage());
            results.add(fieldError.getDefaultMessage());
        }
        return new Response(ResponseCode.REQUEST_PARAM_INVALID,results);
    }
}

